package com.example.guesswho.ui.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.guesswho.ui.components.PrimaryButton
import com.example.guesswho.ui.components.SecondaryButton
import com.example.guesswho.ui.theme.GuessWhoTheme
import kotlinx.coroutines.delay

data class QuestionData(
    val id: String,
    val title: String,
    val coverUrl: String?,
    val clues: List<String>,
    val options: List<String>,
    val correctAnswer: Int
)

data class DanmakuMessage(
    val id: String,
    val username: String,
    val text: String,
    val color: Color = Color.White
)

@Composable
fun GamePlayScreen(
    roomId: String,
    onGameEnd: () -> Unit,
    onShareClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    var currentQuestionIndex by remember { mutableStateOf(0) }
    var currentClueIndex by remember { mutableStateOf(0) }
    var selectedAnswer by remember { mutableStateOf<Int?>(null) }
    var showResult by remember { mutableStateOf(false) }
    var isCorrect by remember { mutableStateOf(false) }
    var timeLeft by remember { mutableStateOf(60) }
    
    val listState = rememberLazyListState()
    
    val sampleQuestions = remember {
        listOf(
            QuestionData(
                id = "q1",
                title = "猜猜我是谁",
                coverUrl = null,
                clues = listOf(
                    "我是一种常见的宠物",
                    "我喜欢吃鱼",
                    "我会抓老鼠",
                    "我喜欢晒太阳",
                    "我会在夜晚活动"
                ),
                options = listOf("狗", "猫", "兔子", "仓鼠"),
                correctAnswer = 1
            ),
            QuestionData(
                id = "q2",
                title = "神秘动物",
                coverUrl = null,
                clues = listOf(
                    "我是世界上最高的动物",
                    "我的脖子很长",
                    "生活在非洲大草原",
                    "以树叶为食",
                    "花纹独特"
                ),
                options = listOf("大象", "长颈鹿", "斑马", "犀牛"),
                correctAnswer = 1
            )
        )
    }
    
    val danmakuMessages = remember {
        mutableStateListOf(
            DanmakuMessage("1", "小明", "太简单了！"),
            DanmakuMessage("2", "小红", "我觉得是猫"),
            DanmakuMessage("3", "小刚", "这题有意思"),
            DanmakuMessage("4", "小美", "选B就对了"),
            DanmakuMessage("5", "小华", "我来啦~"),
            DanmakuMessage("6", "小李", "大家一起加油"),
            DanmakuMessage("7", "小王", "猜对了！"),
            DanmakuMessage("8", "小张", "下一题是什么？")
        )
    }

    LaunchedEffect(Unit) {
        while (timeLeft > 0) {
            delay(1000)
            timeLeft--
            if (timeLeft == 0) {
                onGameEnd()
            }
        }
        
        // Simulate new danmaku messages
        while (true) {
            delay(2000)
            val randomUser = listOf("玩家A", "玩家B", "玩家C", "观众D").random()
            val randomMessage = listOf(
                "加油！", "666", "厉害", "选对了", "猜错了", "哈哈", "有趣", "再来一题"
            ).random()
            danmakuMessages.add(
                DanmakuMessage(
                    id = System.currentTimeMillis().toString(),
                    username = randomUser,
                    text = randomMessage,
                    color = Color.White
                )
            )
        }
    }

    val currentQuestion = sampleQuestions.getOrNull(currentQuestionIndex) ?: sampleQuestions.first()

    Box(
        modifier = modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.background)
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp)
        ) {
            // Header
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 16.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "房间 $roomId",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.onBackground
                )
                
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Schedule,
                        contentDescription = "Time",
                        tint = MaterialTheme.colorScheme.onBackground,
                        modifier = Modifier.size(20.dp)
                    )
                    Text(
                        text = "${timeLeft}s",
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.onBackground
                    )
                }
            }

            // Question Progress
            LinearProgressIndicator(
                progress = (currentQuestionIndex + 1) / sampleQuestions.size.toFloat(),
                modifier = Modifier
                    .fillMaxWidth()
                    .height(8.dp)
                    .clip(RoundedCornerShape(4.dp)),
                color = MaterialTheme.colorScheme.primary,
                trackColor = MaterialTheme.colorScheme.surfaceVariant
            )

            Spacer(modifier = Modifier.height(16.dp))

            // Question Area
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surfaceVariant
                )
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(20.dp),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    Text(
                        text = currentQuestion.title,
                        fontSize = 24.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        textAlign = TextAlign.Center
                    )

                    // Clue Area
                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .weight(1f),
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.surface
                        )
                    ) {
                        Box(
                            modifier = Modifier
                                .fillMaxSize()
                                .padding(16.dp),
                            contentAlignment = Alignment.Center
                        ) {
                            if (currentClueIndex < currentQuestion.clues.size) {
                                Text(
                                    text = currentQuestion.clues[currentClueIndex],
                                    fontSize = 20.sp,
                                    fontWeight = FontWeight.Medium,
                                    color = MaterialTheme.colorScheme.onSurface,
                                    textAlign = TextAlign.Center
                                )
                            }
                        }
                    }

                    // Clue Progress
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = "线索 ${currentClueIndex + 1}/${currentQuestion.clues.size}",
                            fontSize = 14.sp,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        
                        Row(
                            horizontalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            IconButton(
                                onClick = { 
                                    if (currentClueIndex > 0) currentClueIndex--
                                },
                                enabled = currentClueIndex > 0
                            ) {
                                Icon(
                                    imageVector = Icons.Default.KeyboardArrowLeft,
                                    contentDescription = "Previous clue",
                                    tint = if (currentClueIndex > 0) 
                                        MaterialTheme.colorScheme.primary 
                                    else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.3f)
                                )
                            }
                            
                            IconButton(
                                onClick = { 
                                    if (currentClueIndex < currentQuestion.clues.size - 1) currentClueIndex++
                                },
                                enabled = currentClueIndex < currentQuestion.clues.size - 1
                            ) {
                                Icon(
                                    imageVector = Icons.Default.KeyboardArrowRight,
                                    contentDescription = "Next clue",
                                    tint = if (currentClueIndex < currentQuestion.clues.size - 1) 
                                        MaterialTheme.colorScheme.primary 
                                    else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.3f)
                                )
                            }
                        }
                    }

                    // Answer Options
                    if (currentClueIndex >= currentQuestion.clues.size - 1) {
                        Column(
                            modifier = Modifier.fillMaxWidth(),
                            verticalArrangement = Arrangement.spacedBy(12.dp)
                        ) {
                            currentQuestion.options.forEachIndexed { index, option ->
                                AnswerButton(
                                    text = option,
                                    isSelected = selectedAnswer == index,
                                    isCorrect = showResult && index == currentQuestion.correctAnswer,
                                    isWrong = showResult && selectedAnswer == index && index != currentQuestion.correctAnswer,
                                    onClick = {
                                        if (!showResult) {
                                            selectedAnswer = index
                                            isCorrect = index == currentQuestion.correctAnswer
                                            showResult = true
                                        }
                                    }
                                )
                            }
                        }
                    } else {
                        Text(
                            text = "查看所有线索后解锁答案选项",
                            fontSize = 14.sp,
                            color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f),
                            textAlign = TextAlign.Center
                        )
                    }
                }
            }

            Spacer(modifier = Modifier.height(16.dp))

            // Action Buttons
            if (showResult) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    SecondaryButton(
                        text = "分享",
                        onClick = onShareClick,
                        modifier = Modifier.weight(1f)
                    )
                    PrimaryButton(
                        text = if (currentQuestionIndex < sampleQuestions.size - 1) "下一题" else "结束",
                        onClick = {
                            if (currentQuestionIndex < sampleQuestions.size - 1) {
                                currentQuestionIndex++
                                currentClueIndex = 0
                                selectedAnswer = null
                                showResult = false
                            } else {
                                onGameEnd()
                            }
                        },
                        modifier = Modifier.weight(1f)
                    )
                }
            }
        }

        // Danmaku Area
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(120.dp)
                .align(Alignment.BottomCenter)
                .padding(horizontal = 16.dp, vertical = 8.dp)
        ) {
            LazyColumn(
                state = listState,
                modifier = Modifier.fillMaxSize(),
                verticalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                items(danmakuMessages.takeLast(10)) { message ->
                    DanmakuItem(message = message)
                }
            }

            LaunchedEffect(danmakuMessages.size) {
                listState.animateScrollToItem(danmakuMessages.size - 1)
            }
        }
    }
}

@Composable
fun AnswerButton(
    text: String,
    isSelected: Boolean,
    isCorrect: Boolean,
    isWrong: Boolean,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Button(
        onClick = onClick,
        modifier = modifier.fillMaxWidth(),
        colors = ButtonDefaults.buttonColors(
            containerColor = when {
                isCorrect -> MaterialTheme.colorScheme.primaryContainer
                isWrong -> MaterialTheme.colorScheme.errorContainer
                isSelected -> MaterialTheme.colorScheme.primary
                else -> MaterialTheme.colorScheme.surfaceVariant
            },
            contentColor = when {
                isCorrect -> MaterialTheme.colorScheme.onPrimaryContainer
                isWrong -> MaterialTheme.colorScheme.onErrorContainer
                isSelected -> MaterialTheme.colorScheme.onPrimary
                else -> MaterialTheme.colorScheme.onSurfaceVariant
            }
        )
    ) {
        Text(
            text = text,
            fontSize = 16.sp,
            fontWeight = FontWeight.Medium
        )
    }
}

@Composable
fun DanmakuItem(
    message: DanmakuMessage,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier,
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surface.copy(alpha = 0.8f)
        )
    ) {
        Row(
            modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Box(
                modifier = Modifier
                    .size(24.dp)
                    .clip(CircleShape)
                    .background(MaterialTheme.colorScheme.primary),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = message.username.first().toString(),
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.onPrimary
                )
            }
            
            Spacer(modifier = Modifier.width(8.dp))
            
            Text(
                text = "${message.username}: ${message.text}",
                fontSize = 14.sp,
                color = message.color
            )
        }
    }
}

@Preview(showBackground = true, heightDp = 800)
@Composable
fun GamePlayScreenPreview() {
    GuessWhoTheme {
        GamePlayScreen(
            roomId = "room123",
            onGameEnd = {},
            onShareClick = {}
        )
    }
}